<?php

namespace App\Admin\Actions\Post;

use Encore\Admin\Actions\BatchAction;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\Request;
use App\Models\Order;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Auth\Database\OperationLog as OperationLogModel;


class BatchReplicate extends BatchAction
{
    public $name = '批量分配';

    public function handle(Collection $collection, Request $request)
    {
        // 获取到表单中的`type`值
        $type = $request->get('type');

        // 获取表单中的`reason`值
        $people = $request->get('people');

        //只有超管才能批量分配
        $has_auth = Admin::user()->inRoles(['administrator']);
        if(!$has_auth){
            return $this->response()->warning('你没有此操作的权限')->refresh();
        }

        $ids = [];
        foreach ($collection as $key => $model){
            array_push($ids, $model->id);
        }

        $orders = Order::whereIn('id', $ids)->get();
        foreach ($orders as $okey => $oval){
            if($oval->state == 3 || !empty($oval->finished_at)){
                continue;
            }else{
                $oval->repayment_state = $type;
                $oval->collector_id = $people;
                $oval->save();
            }
        }
        $detail = '批量分配操作';
        $this->logoperation($request, $detail);
        return $this->response()->success('成功')->refresh();
    }
    public function form()
    {
        $type = [
            '2' => '委内催收',
            '3' => '委外催收',
        ];

        $this->select('type', '类型')->options($type);
        $this->select('people', '催收员')->options('/admin/common/get/patch/collector');
    }
    //记录操作日志
    public function logoperation($request, $detail){
        $clientip = $request->getClientIp();
        $log = [
            'user_id' => Admin::user()->id,
            'path'    => substr($request->path(), 0, 255),
            'method'  => $request->method(),
            'ip'      => $clientip,
            'input'   => json_encode($request->input()),
            'detail'  => $detail
        ];
        try {
            OperationLogModel::create($log);
        } catch (\Exception $exception) {
            // pass
        }
    }
}